package com.jiangyifen.robot.websocket.internal;

import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.websocket.Session;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class WebsocketCache {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(WebsocketCache.class);

	// 需要单播的websocket消息队列
	public static BlockingQueue<Runnable> unicastQueue = new ArrayBlockingQueue<Runnable>(
			100000);

	public static ThreadPoolExecutor unicastExecutor = new ThreadPoolExecutor(
			10, 20, 5000L, TimeUnit.MILLISECONDS, unicastQueue);

	// 存放所有websocket连接的map，key=客户端唯一标识，常用用户登陆名，value=this(主要是websocket session)
	public static final Map<String, Session> connections = new ConcurrentHashMap<>();

	
	//对于断开的session在这里统一清理
	static {
		Thread cleaner = new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					try {
						for (String clientId : connections.keySet()) {
							Session session = connections.get(clientId);
							if (!session.isOpen()) {
								connections.remove(clientId);
								LOGGER.debug("clean websocket session cache map: clientId = ["
										+ clientId+"]");
							}
							Thread.sleep(10);
						}
						Thread.sleep(1000);
					} catch (Exception e) {
						LOGGER.error(e.getMessage(), e);
					}
				}
			}
		});

		cleaner.setDaemon(true);
		cleaner.start();
	}

}
